#!/usr/bin/python

"""sth.py
Copyright (C) 2009  Ryan Box

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>."""


__author__ = "Ryan Box (coffebean@sbcglobal.net)"
__version__ = "$Revision: 0.0.8 $"
__date__ = "$Date: 12/01/09 $"
__license__ = "Python"

import os
import os.path
import restformat
import time
import hidcheck
import first
from configobj import ConfigObj
from time import asctime


##TO-DO remove test from all rsync t-backuptest.log
#-----------------------------Variables-----------------------------------------
"""If used as a cron job this must be changed to the full path to the file in
your home directory, or where you extracted the folder"""
config = ConfigObj('/home/coffeeboy/Projects/google_code/savethehouse/src/config.ini')

backupruntime = asctime()

backupmedia = config['media']

sourcedir = config['source']

backupdir = backupmedia + config['backupdir']

incrementsdir = backupmedia + config['incsdir']

exclude = sourcedir + config['exlist']

#include = sourcedir + config['inlist']
include =  config['inlist']

log = backupmedia + config['logfile']

hid = config['keephidden']

backupincdir = incrementsdir + backupruntime
#-------------------First run directory creation--------------------------------
def Directorycheck():
    """Check to See that the backup Directory structure has bee created."""
    if not os.path.exists(backupdir):
	first.back(backupdir)

    if not os.path.exists(incrementsdir):
	first.increm(incrementsdir)

    StartLog()

def StartLog():
    """Start the logging for current Backup run."""
    backupincdir = incrementsdir + backupruntime
    backuplog = open(log, 'a')

    print >> backuplog, (restformat.title(backupruntime))
    print >> backuplog, ('Making increments directory: "'+ incrementsdir + backupruntime +'"\n')

    """Make the incrementsdir for current backup and show creation information in
    log file."""
    backupincdir = incrementsdir + backupruntime
    while not os.path.exists(backupincdir):
	os.mkdir(backupincdir)
	time.sleep(5)
	print backupincdir +" created \n"

    #Logging
    print >> backuplog, (restformat.subtitle('BEGIN BACKUP'))
    backuplog.close()
    rsync()

def rsync():
    """Run rsync backup command with Linux logging"""
    backupincdir = incrementsdir + backupruntime

    os.system('rsync -arEtb --delete --stats --log-file-format="%i %o %f %n" --files-from='+include+' --backup-dir='+'"'+backupincdir+'" '+sourcedir+' '+backupdir+'>>'+log)



    ################################################################################
    """launches hicheck to check for hidden files and folders in the
    current backup increments directory"""
    #
    #This is set in config.ini "keephidden" value
    if hid == 'True':
	hidcheck.check(backupincdir)
    elif hid == 'False':
	hidcheck.croncheck(backupincdir)
    #
    ################################################################################
    finalize()

def finalize():
    backupincdir = incrementsdir + backupruntime
    if os.listdir(backupincdir) == []:
	    backuplog = open(log, 'a')
	    print >> backuplog, ('\n')
	    print >> backuplog, ('Nothing sent to'+' ''('+incrementsdir+backupruntime+')'' '+'new increments directory.')
	    print >> backuplog, ('Deleting Empty Directory.')
	    print >> backuplog, ('\n')
	    os.rmdir(incrementsdir + backupruntime)
    else:
	    backuplog = open(log, 'a')
	    print >> backuplog, ('\n')
	    print >> backuplog, ('Files sent to'' '+backupincdir+':')
	    for top, dirs, files in os.walk(backupincdir):
		    for nm in files:
			    print >> backuplog, (os.path.join(top, nm))
	    print >> backuplog, ('\n')

    #Logging
    backuplog = open(log, 'a')
    print >> backuplog, (restformat.subtitle('END BACKUP'))
    print >> backuplog, ('\n\n')
    backuplog.close()
    quit()

if __name__ == "__main__":
    if not os.path.exists(backupdir):
	Directorycheck()
    else:
	StartLog()

